package com.wx.wechat.handler;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Component
public class WeChatHandlerFactory implements InitializingBean {

    @Resource
    private List<WeChatMsgHandler> weChatMsgHandlerList;

    private Map<WxChatMsgTypeEnum,WeChatMsgHandler> handlerMap =new HashMap<>();

    /**
     * 获取消息处理器
     * @throws Exception
     */
    public WeChatMsgHandler getHandler(String type){
        WxChatMsgTypeEnum msgType = WxChatMsgTypeEnum.getByMsgType(type);
        WeChatMsgHandler handler = handlerMap.get(msgType);
        if (handler == null) {
            throw new RuntimeException("未找到对应的消息处理器");
        }
        return handler;
    }

    /**
     * 加载
     * @throws Exception
     */
    @Override
    public void afterPropertiesSet() throws Exception {
        for (WeChatMsgHandler handler : weChatMsgHandlerList){
            handlerMap.put(handler.getType(),handler);
        }
    }
}
